package UDP;

import com.sun.xml.internal.ws.api.ha.StickyFeature;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 功能描述
 *
 * @author wileda
 * @date 2023/02/19  12:06
 */
public class UDPEchoClient {
    private DatagramSocket socket;
    private String serverIp;
    private int serverPort;

    public UDPEchoClient(String serverIp,int serverPort) throws SocketException {
        this.socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        System.out.println("客户端已经启动");
        while (true){
            System.out.println("->");
            Scanner scanner = new Scanner(System.in);
            String request = scanner.nextLine();
            if(request == null || request.equals("")){
                System.out.println("输入了一个空数据。");
                continue;
            }

            SocketAddress address = new InetSocketAddress(serverIp,serverPort);
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),
                    request.getBytes().length,address);
            socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength(),"UTF-8");
            System.out.printf("request = %s, response = %s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        // 初始化客户端服务
        UDPEchoClient client = new UDPEchoClient("127.0.0.1", 9090);
        // 启动服务
        client.start();
    }
}
